package com.atguigu.realtime.demos

import java.util

import com.alibaba.fastjson.{JSON, JSONArray, JSONObject}
import com.google.gson.Gson

/**
 * Created by Smexy on 2022/8/26
 *
 * ts不会覆盖吗?
 *    要的就是覆盖！  如果是actionLog，应该取actionLog中的ts，而不是外层的ts!
 */
object ActionsLogParseDemo {

  def main(args: Array[String]): Unit = {

    val gson = new Gson()

    val str =
      """
        |
        |{
        |"actions":[
        |     {"action_id":"favor_add","item":"538","item_type":"sku_id","ts":1661324222004},
        |     {"action_id":"get_coupon","item":"3","item_type":"coupon_id","ts":1661324228008}
        | ],
        |"common":{"ar":"110000","ba":"iPhone","ch":"Appstore","is_new":"0","md":"iPhone X","mid":"mid_6","os":"iOS 13.3.1","uid":"964","vc":"v2.1.134"},
        |"displays":[{"display_type":"query","item":"10","item_type":"sku_id","order":1,"pos_id":1},{"display_type":"query","item":"595","item_type":"sku_id","order":2,"pos_id":5},{"display_type":"recommend","item":"846","item_type":"sku_id","order":3,"pos_id":5},{"display_type":"query","item":"693","item_type":"sku_id","order":4,"pos_id":3},{"display_type":"query","item":"891","item_type":"sku_id","order":5,"pos_id":2}],
        |"page":{"during_time":18014,"item":"538","item_type":"sku_id","last_page_id":"good_list","page_id":"good_detail","source_type":"activity"},
        |"ts":1661324216000
        |}
        |""".stripMargin


    //把字符串转为Map
    val map: JSONObject = JSON.parseObject(str)
    val commonStr: String = map.getString("common")
    //把common转为map
    val commonMap: JSONObject = JSON.parseObject(commonStr)
    //取出真正存放数据的Map
    val dataMap: util.Map[String, AnyRef] = commonMap.getInnerMap
    //将ts放进去
    dataMap.put("ts",map.getString("ts"))
    //把page部分也放进去
    dataMap.putAll( JSON.parseObject(map.getString("page")).getInnerMap)

    //放入actions部分
    val array: JSONArray = JSON.parseArray(map.getString("actions"))

    for (i <- 0 until array.size()){

      //{"action_id":"favor_add","item":"538","item_type":"sku_id","ts":1661324222004}
      val actionStr: String = array.getString(i)

      val actionMap: util.Map[String, AnyRef] = JSON.parseObject(actionStr).getInnerMap

      //将两个map中的数据合并
      dataMap.putAll(actionMap)

      //写出一次
      println(gson.toJson(dataMap))
    }
  }

}
